//
//  SDP_ViewControllerForFindOutMore.m
//  PRO_B
//
//  Created by sp on 16/3/21.
//  Copyright © 2016年 sp. All rights reserved.
//

#import "SDP_ViewControllerForFindOutMore.h"    //C
#import "LWH_ViewControllerForClickFindOutMore.h"
#import "SDP_PlayerViewController.h"

#import "SDP_CollectionViewCellForFindOutMore.h"    //V
#import "EveryDayTableViewCell.h"
#import "ContentScrollView.h"
#import "ContentView.h"
#import "rilegouleView.h"
#import "CustomView.h"
#import "ImageContentView.h"

#import "SDP_ModelForFindMore.h"    //M
#import "EveryDayModel.h"


#define WIGHT  self.view.bounds.size.width
#define HEIGHT  self.view.bounds.size.height
@interface SDP_ViewControllerForFindOutMore ()<UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property (nonatomic, retain) UICollectionView *collectionViewForFindOutMore;

@property (nonatomic, retain) UICollectionViewFlowLayout *flowLayOutForFindOutMore;

@property (nonatomic, retain) NSMutableArray *arrForFindOutMore;

@property (nonatomic, strong) UIButton *buttonForRight;

@property (nonatomic, strong) UIView *viewForSearch;    //搜索界面

@property (nonatomic, strong) UITableView *tableViewForSearch;  //搜索界面tableView

@property (nonatomic, strong) UITextField *textField;   //搜索界面输入框

@property (nonatomic, strong) NSMutableArray *arrForSearchData; //搜索数据

@property (nonatomic, strong) UILabel *labelForSearch;  //搜索提示

@property (nonatomic, strong) NSString *nextPageUrl;    //上拉刷新url
@end

@implementation SDP_ViewControllerForFindOutMore

#pragma mark  - viewDidLoad
- (void)viewDidLoad {
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //self.tableViewForSearch.autoresizesSubviews
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self  handleDataForFindMore];
    
    [self creatCollectionViewForFindOutMore];
    
    [self settingsNavigationController];

   
}

#pragma mark - 设置naviBar
- (void)settingsNavigationController {
    
    self.buttonForRight = [UIButton buttonWithType:UIButtonTypeSystem];
    
    self.buttonForRight.frame = CGRectMake(0, 0, 30, 30);
    
    self.buttonForRight.titleLabel.font = [UIFont systemFontOfSize:13];
    
    [self.buttonForRight setBackgroundImage:[UIImage imageNamed:@"iconfont-fangdajing"] forState:UIControlStateNormal];
    
    [self.buttonForRight addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.buttonForRight];
    
    
    
    
    self.navigationItem.title = @"开天眼";
    
    
}

#pragma mark - 创建搜索界面
- (void)createSearchView {

    self.viewForSearch = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 0)];
    self.viewForSearch.clipsToBounds = YES;
    self.viewForSearch.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.viewForSearch];
    
    self.labelForSearch = [[UILabel alloc] initWithFrame:CGRectMake(0, 64, kWidth, kWidth / 12)];
    [self.viewForSearch addSubview:self.labelForSearch];
    self.labelForSearch.textAlignment = 1;
    self.labelForSearch.text = @"请输入视频标题或描述中的关键词进行搜索";
    self.labelForSearch.font = [UIFont systemFontOfSize:10];
    self.labelForSearch.backgroundColor = [UIColor whiteColor];
    
}

#pragma mark - 创建搜索界面的tableView
- (void)createTableView {
    
    self.tableViewForSearch = [[UITableView alloc] initWithFrame:CGRectMake(0, kWidth / 12 + 64, kWidth, kHeight - 64 - kWidth / 12) style:UITableViewStylePlain];
    [self.viewForSearch addSubview:self.tableViewForSearch];
    
    self.tableViewForSearch.dataSource = self;
    self.tableViewForSearch.delegate = self;
    
    [self.tableViewForSearch registerClass:[EveryDayTableViewCell class] forCellReuseIdentifier:@"cellForSearchView"];
    
    self.tableViewForSearch.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [NetWorkHandler networkingWithUrl:self.nextPageUrl comleteHandle:^(id result , NSData *data) {
                
                self.nextPageUrl = [result objectForKey:@"nextPageUrl"];
                
                NSArray *arr = [result objectForKey:@"itemList"];
                for (NSDictionary *dic in arr) {
                    EveryDayModel *model = [[EveryDayModel alloc] init];
                    NSDictionary *dicTemp = [dic objectForKey:@"data"];
                    [model setValuesForKeysWithDictionary:dicTemp];
                    [self.arrForSearchData addObject:model];
                    
                }
                
                [self.tableViewForSearch reloadData];
                [self.tableViewForSearch.mj_footer endRefreshing];
                
                if ([self.nextPageUrl isEqual:[NSNull null]]) {
                    
                    self.tableViewForSearch.mj_footer.hidden = YES;
                    
                    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kWidth, 40)];
                    label.text = @"- The End -";
                    label.textAlignment = 1;
                    label.font = [UIFont fontWithName:@"AmericanTypewriter-Bold" size:15];
                    self.tableViewForSearch.tableFooterView = label;
                    
                }
                
            }];
            
        });
    }];

    
}

#pragma mark - 创建搜索界面textField

- (void)createTextField {
    
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, kWidth - 50, 25)];
    self.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.textField.textAlignment = 1;
    self.textField.layer.cornerRadius = self.textField.frame.size.height / 2;
    self.textField.layer.masksToBounds = YES;
    self.textField.font = [UIFont systemFontOfSize:13];
    self.textField.backgroundColor = [UIColor grayColor];
    self.textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"帮你快速找到往期视频" attributes:@{NSForegroundColorAttributeName:[UIColor lightGrayColor]}];
    
    self.textField.delegate = self;
    
    self.navigationItem.titleView = self.textField;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if ([textField.text isEqualToString:@""]) {
        return YES;
    }
    
    [self handleDataForSearch];
    
    [textField resignFirstResponder];
    
    return YES;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return kHeight / 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.arrForSearchData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EveryDayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellForSearchView"];
   // cell.backgroundColor = [UIColor redColor];
    return cell;
}

#pragma mark - 搜索按钮Action
- (void)buttonAction:(UIButton *)button {
    button.selected ^= 1;
    
    if (button.selected) {
        
        [self.buttonForRight setTitle:@"取消" forState:UIControlStateNormal];
        [self.buttonForRight setBackgroundImage:nil forState:UIControlStateNormal];
        self.buttonForRight.tintColor = [UIColor clearColor];
        [self.buttonForRight setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        
        if (!(self.viewForSearch != nil)) {
            [self createSearchView];
            
        }
        
        [self createTextField];
        
        // 隐藏自定义TabBar
        [[NSNotificationCenter defaultCenter] postNotificationName:@"隐藏" object:nil];
        
        [UIView animateWithDuration:0.25 animations:^{
            
            self.viewForSearch.frame = CGRectMake(0, 0, kWidth, kHeight);
            
        }];
        
    } else {
        
        
        [self.buttonForRight setTitle:nil forState:UIControlStateNormal];
        
        [self.buttonForRight setBackgroundImage:[UIImage imageNamed:@"iconfont-fangdajing"] forState:UIControlStateNormal];
        
        [self.textField removeFromSuperview];
        [self.rilegoule removeFromSuperview];
        [self.tableViewForSearch removeFromSuperview];
        
        
        // 显示自定义TabBar
        [[NSNotificationCenter defaultCenter] postNotificationName:@"显示" object:nil];
        
        [UIView animateWithDuration:0.25 animations:^{
            
            self.viewForSearch.frame = CGRectMake(0, 0, kWidth, 0);
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
            label.text = @"开天眼";
            label.textAlignment = 1;
            self.navigationItem.titleView = label;
            
            self.labelForSearch.text = @"帮你快速找到往期视频";
            
        }];
        
        
        
    }
    
}
//添加每个cell出现时的3D动画
-(void)tableView:(UITableView *)tableView willDisplayCell:(EveryDayTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //        CATransform3D rotation;//3D旋转
    //
    //        rotation = CATransform3DMakeTranslation(0 ,50 ,20);
    ////        rotation = CATransform3DMakeRotation( M_PI_4 , 0.0, 0.7, 0.4);
    //        //逆时针旋转
    //
    //        rotation = CATransform3DScale(rotation, 0.9, .9, 1);
    //
    //        rotation.m34 = 1.0/ -600;
    //
    //        cell.layer.shadowColor = [[UIColor blackColor]CGColor];
    //        cell.layer.shadowOffset = CGSizeMake(10, 10);
    //        cell.alpha = 0;
    //
    //        cell.layer.transform = rotation;
    //
    //        [UIView beginAnimations:@"rotation" context:NULL];
    //        //旋转时间
    //        [UIView setAnimationDuration:0.6];
    //        cell.layer.transform = CATransform3DIdentity;
    //        cell.alpha = 1;
    //        cell.layer.shadowOffset = CGSizeMake(0, 0);
    //        [UIView commitAnimations];
    
    
    [cell cellOffset];
    
    EveryDayModel *model = [self.arrForSearchData objectAtIndex:indexPath.row];
    
    [cell setModel:model];
}




- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self showImageAtIndexPath:indexPath];
    
}


#pragma mark - 设置详情界面
- (void)showImageAtIndexPath:(NSIndexPath *)indexPath{
    
    _array = self.arrForSearchData;
    
    _currentIndexPath = indexPath;
    
    EveryDayTableViewCell *cell = [self.tableViewForSearch cellForRowAtIndexPath:indexPath];
    CGRect rect = [cell convertRect:cell.bounds toView:nil];
    CGFloat y = rect.origin.y;
    
    _rilegoule = [[rilegouleView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight) imageArray:_array index:indexPath.row];
    _rilegoule.offsetY = y;
    _rilegoule.animationTrans = cell.picture.transform;
    _rilegoule.animationView.picture.image = cell.picture.image;
    
    _rilegoule.scrollView.delegate = self;
    
    [[self.tableViewForSearch superview] addSubview:_rilegoule];
    
    
    //添加轻扫手势
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    
    _rilegoule.contentView.userInteractionEnabled = YES;
    
    swipe.direction = UISwipeGestureRecognizerDirectionUp;
    
    [_rilegoule.contentView addGestureRecognizer:swipe];
    
    //添加点击播放手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [_rilegoule.scrollView addGestureRecognizer:tap];
    
    [_rilegoule aminmationShow];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"隐藏" object:nil];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    

    if ([scrollView isEqual:_rilegoule.scrollView]) {
        
        
        for (ImageContentView *subView in scrollView.subviews) {
            
            if ([subView respondsToSelector:@selector(imageOffset)] ) {
                [subView imageOffset];
            }
        }
        
        CGFloat x = _rilegoule.scrollView.contentOffset.x;
        
        CGFloat off = ABS( ((int)x % (int)kWidth) - kWidth/2) /(kWidth/2) + .2;
        
        [UIView animateWithDuration:1.0 animations:^{
            _rilegoule.playView.alpha = off;
            _rilegoule.contentView.titleLabel.alpha = off + 0.0;
            _rilegoule.contentView.littleLabel.alpha = off + 0.0;
            _rilegoule.contentView.lineView.alpha = off + 0.0;
            _rilegoule.contentView.descripLabel.alpha = off + 0.0;
            _rilegoule.contentView.collectionCustom.alpha = off + 0.0;
            _rilegoule.contentView.shareCustom.alpha = off + 0.0;
            _rilegoule.contentView.cacheCustom.alpha = off + 0.0;
            _rilegoule.contentView.replyCustom.alpha = off + 0.0;
            
        }];
        
    } else {
        
        NSArray<EveryDayTableViewCell *> *array = [self.tableViewForSearch visibleCells];
        
        [array enumerateObjectsUsingBlock:^(EveryDayTableViewCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [obj cellOffset];
        }];
        
    }
    
    
}

// 滑动将要结束
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    
    if ([scrollView isEqual:_rilegoule.scrollView]) {
        
        int index = floor((_rilegoule.scrollView.contentOffset.x - scrollView.frame.size.width / 2) / scrollView.frame.size.width) + 1;
        
        
        
        _rilegoule.scrollView.currentIndex = index;
        
        self.currentIndexPath = [NSIndexPath indexPathForRow:index inSection:self.currentIndexPath.section];
        
        [self.tableViewForSearch scrollToRowAtIndexPath:self.currentIndexPath atScrollPosition:(UITableViewScrollPositionMiddle) animated:NO];
        
        [self.tableViewForSearch setNeedsDisplay];
        EveryDayTableViewCell *cell = [self.tableViewForSearch cellForRowAtIndexPath:self.currentIndexPath];
        
        [cell cellOffset];
        
        CGRect rect = [cell convertRect:cell.bounds toView:nil];
        _rilegoule.animationTrans = cell.picture.transform;
        _rilegoule.offsetY = rect.origin.y;
        
        EveryDayModel *model = _array[index];
        
        [_rilegoule.contentView setData:model];
        
        [_rilegoule.animationView.picture sd_setImageWithURL:[NSURL URLWithString:[model.cover objectForKey:@"feed"]] placeholderImage:nil];
        
    }
    
    
}

#pragma mark - 平移手势触发事件
- (void)panAction:(UISwipeGestureRecognizer *)swipe{
    
   //[[NSNotificationCenter defaultCenter] postNotificationName:@"显示" object:nil];
    [_rilegoule animationDismissUsingCompeteBlock:^{
        
        _rilegoule = nil;

    }];
    
}

#pragma mark - 点击手势
- (void)tapAction{
    
    SDP_PlayerViewController *playerVC = [[SDP_PlayerViewController alloc] init];
    playerVC.modelArray = self.array;
    playerVC.indexForMovie = self.currentIndexPath.row;
    [self presentViewController:playerVC animated:YES completion:nil];
}



#pragma mark - 创建collectionView
/** FlowLayout 布局 */
- (void)creatFlowLayoutView{
    
    self.flowLayOutForFindOutMore = [[UICollectionViewFlowLayout alloc] init];
    
    // Item size
    self.flowLayOutForFindOutMore.itemSize = CGSizeMake((WIGHT - 1) / 2.0 , (WIGHT - 1) / 2.0);
    
    // Item 之间最小间距
    self.flowLayOutForFindOutMore.minimumInteritemSpacing = 1;//横向,最小间距
    self.flowLayOutForFindOutMore.minimumLineSpacing = 1;//纵向;最小间距
    
    //分区边缘距离
    self.flowLayOutForFindOutMore.sectionInset = UIEdgeInsetsMake(WIGHT / 60, 0, WIGHT / 60, 0);
    
}

- (void)creatCollectionViewForFindOutMore{
    
    
    [self creatFlowLayoutView];
    
    /** 创建对象 **/
    self.collectionViewForFindOutMore = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64 - 49) collectionViewLayout:self.flowLayOutForFindOutMore];
    
    /** 背景颜色 */

     self.collectionViewForFindOutMore.backgroundColor = [UIColor whiteColor];
    
    /** 隐藏滑动条 */
    
     self.collectionViewForFindOutMore.showsVerticalScrollIndicator = NO;
    
    [self.view addSubview: self.collectionViewForFindOutMore];
    
   /** 代理*/
    
     self.collectionViewForFindOutMore.dataSource = self;
     self.collectionViewForFindOutMore.delegate = self;
    
    //注册 cell
    
     [ self.collectionViewForFindOutMore registerClass:[SDP_CollectionViewCellForFindOutMore class] forCellWithReuseIdentifier:@"poolForCollectionViewCell"];
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.arrForFindOutMore.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    SDP_CollectionViewCellForFindOutMore *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolForCollectionViewCell" forIndexPath:indexPath];
    SDP_ModelForFindMore *model = [self.arrForFindOutMore objectAtIndex:indexPath.item];
    [cell passModelForFindMore:model];

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"点击了第%ld个item.", indexPath.item);
    SDP_ModelForFindMore *model = [self.arrForFindOutMore objectAtIndex:indexPath.item];
    NSString *str = [NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v3/videos?_s=f788f74090664ea1b0b1d6cbe677e9da&categoryId=%@&f=iphone&net=wifi&num=20&start=0&strategy=date&u=693b683a5db7a43954ed61f0fad8d5f216b94455&v=1.12.1&vc=403", model.id];
    LWH_ViewControllerForClickFindOutMore *vc = [[LWH_ViewControllerForClickFindOutMore alloc] init];
    vc.url = str;
    vc.ID = model.id;
    [self.navigationController pushViewController:vc animated:YES];
    
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.textField resignFirstResponder];
}




#pragma mark - 解析数据
- (void)handleDataForFindMore{
    
    NSString *urlForFindMore = @"http://baobab.wandoujia.com/api/v2/categories?_s=916fd1ff41d64be0564680381c26d1b3&f=iphone&net=wifi&u=693b683a5db7a43954ed61f0fad8d5f216b94455&v=1.12.0&vc=312";
    
    [NetWorkHandler networkingWithUrl:urlForFindMore comleteHandle:^(id result, NSData *data) {
        
        self.arrForFindOutMore = [NSMutableArray array];
        
        for (NSDictionary *dicForFindData  in result) {
            SDP_ModelForFindMore *model = [[SDP_ModelForFindMore alloc]init];
            [model setValuesForKeysWithDictionary:dicForFindData];
            [self.arrForFindOutMore addObject:model];
            
        }
        
        [self.collectionViewForFindOutMore reloadData];
        
    }];
    
}

- (void)handleDataForSearch {
    
    NSString *url = [NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v1/search?_s=974ee9f4921fc08c864dca80bb17d7c4&f=iphone&net=wifi&num=20&query=%@&u=693b683a5db7a43954ed61f0fad8d5f216b94455&v=1.12.1&vc=403", self.textField.text];
    
    [NetWorkHandler networkingWithUrl:url comleteHandle:^(id result, NSData *data) {
       
        NSString *total = [NSString stringWithFormat:@"%@", [result objectForKey:@"total"]];
        self.nextPageUrl = [result objectForKey:@"nextPageUrl"];
        
        if ([total isEqualToString:@"0"]) {
            
            
        } else {
            self.arrForSearchData = [NSMutableArray array];
            NSArray *arr = [result objectForKey:@"itemList"];
            for (NSDictionary *dic in arr) {
                NSDictionary *data = [dic objectForKey:@"data"];
                EveryDayModel *model = [[EveryDayModel alloc] init];
                [model setValuesForKeysWithDictionary:data];
                [self.arrForSearchData addObject:model];
            }
            [self createTableView];
            [self.tableViewForSearch reloadData];
            NSString *temp = [NSString stringWithFormat:@"- 「 %@ 」搜索结果共%@个 -", self.textField.text, total];
            self.labelForSearch.text = temp;
            [self.viewForSearch bringSubviewToFront:self.labelForSearch];
            
            
            if ([self.nextPageUrl isEqual:[NSNull null]]) {
                
                self.tableViewForSearch.mj_footer.hidden = YES;
                
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kWidth, 40)];
                label.text = @"- The End -";
                label.textAlignment = 1;
                label.font = [UIFont fontWithName:@"AmericanTypewriter-Bold" size:15];
                self.tableViewForSearch.tableFooterView = label;
                
            }

        }
    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
